package dtm

import (
	"context"
	"database/sql"

	// "fmt"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/resultx"
	"mall/service/backend/common/i18n"
	"mall/service/promotion/model"
	"mall/service/promotion/rpc/internal/svc"
	"mall/service/promotion/rpc/types/promotion"

	"github.com/dtm-labs/client/dtmcli"
	"github.com/dtm-labs/client/dtmgrpc"

	// "github.com/sirupsen/logrus"
	"github.com/volatiletech/null/v8"
	"github.com/volatiletech/sqlboiler/v4/boil"
	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
)

type ExchangeCouponRawLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewExchangeCouponRawLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ExchangeCouponRawLogic {
	return &ExchangeCouponRawLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ExchangeCouponRawLogic) ExchangeCouponRaw(in *promotion.CouponInfo) (*promotion.BaseResp, error) {
	// logrus.Info(fmt.Sprintf("ExchangeCouponRaw: %+v", in))
	logx.Infof("ExchangeCouponRaw : %+v ", in)
	// UserId:10001 OrderId:8 Logs:{ActivityId:2 ActivityRuleId:2 CouponTemplateId:0 CouponId:0} Logs:{ActivityId:1 ActivityRuleId:1 CouponTemplateId:0 CouponId:0} Logs:{ActivityId:0 ActivityRuleId:0 CouponTemplateId:1 CouponId:1}

	if in.TemplateId == nil || *in.TemplateId == 0 {
		return nil, resultx.StatusError(resultx.COUPON_ID_REQUIRED, "")
	}

	if in.UserId == nil || *in.UserId == 0 {
		return nil, resultx.StatusError(resultx.USER_ID_REQUIRED, "")
	}

	if in.StartedAt == nil || in.EndedAt == nil || len(*in.StartedAt) == 0 || len(*in.EndedAt) == 0 {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	var startedAt time.Time
	if localTime, err := modelx.ParseLocalTime(*in.StartedAt); err == nil {
		startedAt = localTime
	} else {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	var endedAt time.Time
	if localTime, err := modelx.ParseLocalTime(*in.EndedAt); err == nil {
		endedAt = localTime
	} else {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	// 获取子事务屏障对象
	barrier, err := dtmgrpc.BarrierFromGrpc(l.ctx)
	if err != nil {
		return nil, resultx.StatusError(resultx.DTM_ERROR, err.Error())
	}

	// 开启子事务屏障
	err = barrier.CallWithDB(l.svcCtx.DB, func(tx *sql.Tx) error {
		now := time.Now()
		coupon := &model.PromotionCoupon{
			TemplateID: *in.TemplateId,
			UserID:     *in.UserId,
			StartedAt:  null.TimeFrom(startedAt),
			EndedAt:    null.TimeFrom(endedAt),
			CreatedAt:  now,
			UpdatedAt:  now,
			Status:     uint16(globalkey.StatusStarted),
		}
		if in.ActivityId != nil && *in.ActivityId > 0 {
			coupon.ActivityID = *in.ActivityId
		}
		err = coupon.Insert(l.ctx, tx, boil.Infer())
		if err != nil {
			logx.Errorw("ExchangeCouponRaw Insert err", logx.Field("detail", err.Error()))
		}

		log := &model.PromotionCouponOprLog{
			CouponID:  coupon.CouponID,
			UserID:    *in.UserId,
			Type:      uint8(globalkey.CouponOprTypeExchange),
			Status:    uint16(globalkey.StatusEnabled),
			CreatedAt: now,
		}
		err = log.Insert(l.ctx, tx, boil.Infer())
		if err != nil {
			logx.Errorw("ExchangeCouponRaw PromotionCouponOprLog Insert err", logx.Field("detail", err.Error()))
		}

		return nil
	})

	// 不再重试，走回滚
	if err == dtmcli.ErrFailure {
		return nil, resultx.StatusError(uint32(codes.Aborted), dtmcli.ResultFailure)
	}

	if err != nil {
		return nil, err
	}

	return &promotion.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
